package org.lewis.man.controllers;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.lewis.common.Constants;
import org.lewis.common.domain.EmailTask;
import org.lewis.common.domain.User;
import org.lewis.common.domain.VCode;
import org.lewis.common.email.EmailService;
import org.lewis.common.service.UserService;
import org.lewis.common.service.VCodeService;
import org.lewis.common.utils.WebUtils;

import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.HttpUtils;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TemplateRenderer;

/**
 * 找回密码
 * 
 * @author taiqichao
 * 
 */
@Controller
@NameSpace("/accounts")
public class AccountResetPwdController {

	private final static String VIEWBASEPATH = "/WEB-INF/views/accounts";

	@Injection
	private UserService userService;

	@Injection
	private EmailService emailService;
	
	@Injection
	private VCodeService vcodeService;
	
	
	private void toIndex() throws IOException {
		User user = (User) WebUtils.getSession().getAttribute(Constants.CURRENTUSER);
		if (user != null) {
			WebUtils.getResponse().sendRedirect(HttpUtils.getContentPath());
		}
	}
	
	/**
	 * 重置密码
	 * @return
	 * @throws Exception
	 */
	@Mapping("/resetpassword")
	public Renderer validateRest() throws Exception {
		
		toIndex();

		if (WebUtils.isPost()) {
			
			// 校验tokenid
			String clientTokenId = WebUtils.getParameter("tokenid");
			
			String sessionTokenId = (String) WebUtils.getSession().getAttribute("tokenid");
			
			if (!clientTokenId.equals(sessionTokenId)) {
				// 生成tokenid
				WebUtils.getSession().setAttribute("tokenid",UUID.randomUUID().toString());
				return new TemplateRenderer(VIEWBASEPATH+ "/find_password.vm");
			}

			Map<String, Object> model = new HashMap<String, Object>();

			String email = WebUtils.getParameter("form_email");

			User user = userService.getUserByEmail(email);

			if (user != null) {
				String key=null;
				VCode vcode=vcodeService.getByCode(user.getId(),VCode.TYPE.FINDPWD.name());
				if(null!=vcode){
					key=vcode.getCode();
				}else{
					key=UUID.randomUUID().toString();
					vcode=new VCode();
					vcode.setCode(key);
					vcode.setType(VCode.TYPE.FINDPWD.name());
					vcode.setUid(user.getId());
					vcodeService.addVCode(vcode);
				}
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("base", HttpUtils.getContentPath());
				data.put("name", user.getName());
				data.put("key", key);
				
				emailService.sendEmail(EmailTask.TYPE.account.name(),
						EmailTask.SENDTYPE.immediately.name(),
						"/WEB-INF/views/common/findpwd.vm", 
						"重设"+ user.getName() + "在Love的密码",
						email, data);

				model.put("email", email);
			} else {
				model.put("msg", "邮箱不存在，请检查您输入的邮箱！");
			}
			
			// 生成tokenid
			WebUtils.getSession().setAttribute("tokenid",UUID.randomUUID().toString());

			return new TemplateRenderer(VIEWBASEPATH+ "/find_password_result.vm", model);
		}
		
		User user=(User) WebUtils.getSession().getAttribute(Constants.CURRENTUSER);
		if(user!=null){
			WebUtils.getResponse().sendRedirect(HttpUtils.getContentPath()+"/people/"+user.getName());
		}
		
		// 生成tokenid
		WebUtils.getSession().setAttribute("tokenid",UUID.randomUUID().toString());

		return new TemplateRenderer(VIEWBASEPATH + "/find_password.vm");
	}

	

	/**
	 * 重置页面
	 * @param key
	 * @param uid
	 * @return
	 * @throws Exception
	 */
	@Mapping("/resetpassword/$1")
	public Renderer toRest(String key) throws Exception {
		this.toIndex();
		VCode vCode=vcodeService.getByCode(key);
		if(vCode==null){
			return new TemplateRenderer(VIEWBASEPATH + "/reset_password_result.vm");
		}
		User user = userService.getUserById(vCode.getUid());
		if (user != null) {
			if (vCode.getCode().equals(key)) {
				Map<String, Object> data=new HashMap<String, Object>();
				data.put("key", key);
				return new TemplateRenderer(VIEWBASEPATH+ "/resetpassword.vm",data);
			}
		}
		//验证失败
		return new TemplateRenderer(VIEWBASEPATH + "/reset_password_result.vm");
	}
	/**
	 * 处理密码重置
	 * @return
	 * @throws Exception
	 */
	@Mapping("/doresetpassword")
	public Renderer doRest() throws Exception {
		this.toIndex();
		if (WebUtils.isPost()) {
			String key=WebUtils.getParameter("key");
			VCode vCode=vcodeService.getByCode(key);
			if(vCode==null){
				return new TemplateRenderer(VIEWBASEPATH + "/reset_password_result.vm");
			}
			String pwd=WebUtils.getParameter("form_password");
			User user = userService.getUserById(vCode.getUid());
			if (user != null) {
				if (vCode.getCode().equals(key)) {
					//更新密码
					userService.updateUserPassword(user.getId(), pwd);
					vcodeService.removeCode(vCode.getId());
					//登录跳转
					WebUtils.getSession().setAttribute(Constants.CURRENTUSER, user);
					WebUtils.getResponse().sendRedirect(HttpUtils.getContentPath());
				}
			}
		}
		//验证失败
		return new TemplateRenderer(VIEWBASEPATH + "/reset_password_result.vm");
	}
	

}
